import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:test01/okhttp_test/page/pages/carousel_map.dart';
import 'package:test01/okhttp_test/pojo/commentdto_pojo.dart';
import 'package:test01/okhttp_test/pojo/login_request_pojo.dart';
import 'package:test01/okhttp_test/provider/searchwords.dart';
import 'package:test01/okhttp_test/util/request_http.dart';

import '../../util/Interceptor.dart';


/*
*
* 动态列表界面展示
*
* */

class vidoList extends StatefulWidget{
  // const vidoList({Key key,this.controller}) : super(key: key);
  // final ScrollController controller;

  const vidoList({Key key,}) : super(key: key);


  @override
  VidoListState createState() => VidoListState();
}

///设置初始加载的数据
int size=10;




class VidoListState extends State<vidoList>  with AutomaticKeepAliveClientMixin{
  List<ListModel> listModel = [];
  CommentDto commentDto;

  ///控制器
  ScrollController controller=ScrollController();
  ///数据加载状态
  bool isLoding=false;

  int lastTime;

  String url_interface="/appuser/web/feed/pullList";

  @override
  void initState() {
    // TODO: implement initState
    ///初始化界面数据
    init();
    print("调用-----------------------------------------------------调用完毕");
    controller.addListener(() {
      if(controller.position.pixels==controller.position.maxScrollExtent){
        print("滑动到了底部");
        // getListModelMore();
        ///上拉刷新
        mmmm();
      }
    });
    super.initState();
  }
  ///上拉刷新
 mmmm() async {
    if(lastTime!=null){
      CommentDto commentDtoList=  await  getlistmodelmore( lastTime, size,url_interface) ;
      commentDtoList.list.forEach((element) {
        listModel.add(element);
      });
      commentDto=commentDtoList;
      setState(() {});
    }
    lastTime=commentDto.lastTime;
}



///初始化界面数据--获取匿名token和界面数据
init() async{
    listModel=[];
    print("33333333333333333333333333333333333333333");
    LoginRequst loginRequst=LoginRequst(grant_type:"anonymous",authorization: "Basic dXNlckFwcDpBaW15Rml0bmVzcw==");
    LoginRespons loginRespons=await getinittokens(loginRequst, "/uaa/oauth/login");
    tokens="${loginRespons.token_type} ${loginRespons.access_token}";
    print("222222222222222222222222222222222222");


    CommentDto commentDtoList=await aa(size,url_interface);
    commentDtoList.list.forEach((element) {
      listModel.add(element);
    });
    commentDto=commentDtoList;
    lastTime=commentDto.lastTime;

    setState(() {
    });
}



  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        body:
        RefreshIndicator(
          onRefresh: () async {
            listModel=[];
              init();
          },
          child:
          ListView.separated(
          itemBuilder: (BuildContext context, int index) {
            return Container(child: ListItem(listmodel: listModel[index]));
          },
          separatorBuilder: (BuildContext context, int index) {
            return Divider();
          },
          itemCount: listModel.length,
            // controller: widget.controller,

        )
        )
    );
  }

  @override
  void dispose() {
    super.dispose();
    controller.dispose();
  }



  ///状态保存
  @override
  bool get wantKeepAlive => true;
}

class ListItem extends StatelessWidget {
  ListModel listmodel;
  double proportion;
  String creatTime;
  double proportion_height;
  int stemp_wrong, laudCount;
  int laudCount_img;//点赞图片数量

  ListItem({Key key, this.listmodel}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    //时间戳转换
    DateTime createTimes =
        DateTime.fromMillisecondsSinceEpoch(listmodel.createTime);
    //获取当前时间
    DateTime nowTime = DateTime.now();
    //时间戳之差
    stemp_wrong = nowTime.millisecondsSinceEpoch - listmodel.createTime;
    //判断出现时间状态
    if (createTimes.year != nowTime.year) {
      creatTime =
          "${((createTimes.year) % 100).toStringAsFixed(0)}-${(createTimes.month).toStringAsFixed(0)}-${(createTimes.day).toStringAsFixed(0)}"
          "  ${(createTimes.hour).toStringAsFixed(0)}:${(createTimes.minute).toStringAsFixed(0)}";
    } else if ((createTimes.day+1) == nowTime.day) {
      creatTime = "昨天 ${createTimes.hour}:${createTimes.minute}";
    } else if (0 <= stemp_wrong && stemp_wrong < (1000 * 60)) {
      creatTime = "刚刚";
    } else if ((1000 * 60) <= stemp_wrong && stemp_wrong < (1000 * 60 * 60)) {
      if ((stemp_wrong / (1000 * 60)).round() == 1) {
        creatTime = "2分钟前";
      } else {
        creatTime = "${((stemp_wrong / (1000 * 60)).round()).toString()}分钟前";
      }
    } else if ((1000 * 60 * 60) <= stemp_wrong &&
        stemp_wrong < (1000 * 60 * 60 * 24)) {
      creatTime = "${(stemp_wrong / (1000 * 60 * 60)).round()}小时前";
    } else if ((1000 * 60 * 60 * 24) <= stemp_wrong &&
        stemp_wrong < (1000 * 60 * 60 * 48)) {
      if ((stemp_wrong - (1000 * 60 * 60 * 24)) == 0) {
        creatTime = "昨天 00:00";
      } else {
        creatTime = "昨天 ${createTimes.hour}:${createTimes.minute}";
      }
    } else {
      creatTime =
          "${createTimes.month}-${createTimes.day}  ${createTimes.hour}:${createTimes.minute}";
    }

    ///比例计算以及条件判定
    if (listmodel.picUrls.length != 0) {
      proportion = MediaQuery.of(context).size.width /
          listmodel.picUrls[0].width.toDouble();
      proportion_height = listmodel.picUrls[0].height.toDouble() * proportion;

      ///阀值比较
      if(listmodel.picUrls[0].width > listmodel.picUrls[0].height){
        if(MediaQuery.of(context).size.width/proportion_height>1.9){
          proportion_height=MediaQuery.of(context).size.width/1.9;
        }
      }else{
        if(MediaQuery.of(context).size.width/proportion_height<0.8){
          proportion_height=MediaQuery.of(context).size.width/0.8;
        }
      }

    } else if (listmodel.videos.length != 0) {
      //video宽度
      if (listmodel.videos[0].width != 0 && listmodel.videos[0].height != 0) {
        proportion = MediaQuery.of(context).size.width /
            listmodel.videos[0].width.toDouble();
        proportion_height = listmodel.videos[0].height.toDouble()* proportion;
      } else {
        proportion_height = MediaQuery.of(context).size.width;
      }
      ///阀值比较
      if(listmodel.videos[0].width > listmodel.videos[0].height){
        if(MediaQuery.of(context).size.width/proportion_height>1.9){
          proportion_height=MediaQuery.of(context).size.width/1.9;
        }
      }else{
        if(MediaQuery.of(context).size.width/proportion_height<0.8){
      proportion_height=MediaQuery.of(context).size.width/0.8;
        }
      }
    }

    ///评论判定
    if (listmodel.comments.length > 1) {
      laudCount = 2;
    } else if (listmodel.comments.length > 0) {
      laudCount = 1;
    } else {
      laudCount = 0;
    }

    ///点赞图片数量控制
    if(listmodel.laudUserInfos.length!=0){
      laudCount_img=listmodel.laudUserInfos.length;
    }else{
      laudCount_img=0;
    }

    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        ///头部
        Container(
          height: 64,
          width: MediaQuery.of(context).size.width,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              ///人物头像
              Container(
                margin: EdgeInsets.only(left: 16),
                child: ClipOval(
                  child: Image.network(
                    listmodel.avatarUrl,
                    height: 38,
                    width: 38,
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              Container(
                width: MediaQuery.of(context).size.width - 32 - 38 - 11 - 70 -24-10,
                  margin: EdgeInsets.only(left: 11),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      ///用户名
                      Text(
                        listmodel.name,
                        style: TextStyle(
                          fontSize: 15,
                          fontWeight: FontWeight.w500,
                        ),
                        overflow: TextOverflow.ellipsis,
                        maxLines: 1,
                      ),
                      // ),

                      ///时间
                      Text(
                        creatTime,
                        style: TextStyle(
                            fontSize: 13, color: Colors.black.withOpacity(0.6)),
                      ),
                    ],
                  )),

              ///占领剩余的空间
              Spacer(),

              ///按钮
              Container(
                width: 70,
                height: 30,
                decoration: BoxDecoration(
                    border: Border.all(
                      color: Colors.black.withOpacity(0.5),
                      width: 1,
                    ),
                    borderRadius: BorderRadius.circular(30)),
                child: Row(
                  children: <Widget>[
                    Container(
                      margin: EdgeInsets.fromLTRB(5, 0, 0, 0),
                      child: Icon(
                        Icons.add,
                        size: 18,
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.fromLTRB(2, 0, 0, 0),
                      child: Text(context.read<IsFollow>().recent_search.length==0?"关注":"已关注",style: TextStyle(fontSize: 10),),
                    ),
                  ],
                ),
              ),
              Container(
                width: 24,
                height: 24,
                alignment: Alignment.topLeft,
                child:
                GestureDetector(
                  onTap: (){
                    ///底部提示框
                    showModal(context);
                  },
                  child:  Icon(Icons.wrap_text),
                ),
              ),

              ///距离边界的距离
              SizedBox(
                width: 16,
              )
            ],
          ),
        ),

        ///中部图片
        Container(
            margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
            //获取屏幕的宽度
            width: MediaQuery.of(context).size.width,

            child: SwiperPage(listmodel,proportion_height)),

        ///点赞
        Container(

          margin: EdgeInsets.only(left: 16),

          child: Row(
            children: <Widget>[
              ///头像图片
              laudCount_img>0 ?Stack(
                  children:
                  List.generate(laudCount_img, (index) {
                    return Container(
                      margin: EdgeInsets.only(right: index*10.toDouble()),
                      child: ClipOval(
                        child: Image.network(
                          listmodel.laudUserInfos[index].avatarUri,
                          height: 21,
                          width: 21,
                          fit: BoxFit.cover,
                        ),
                      ),
                    );
                  }),
                textDirection: TextDirection.rtl,
              ):Container(),

              Container(
                margin: EdgeInsets.only(left: 5),
                child: Text(
                  "${listmodel.laudCount}次赞",
                  style: TextStyle(color: Colors.black.withOpacity(0.8)),
                ),
              ),
              Spacer(),

              ///右侧图标
              Container(
                child: Icon(
                  Icons.accessibility_rounded,
                  size: 25,
                  color: Colors.black.withOpacity(0.6),
                ),
              ),
              Container(
                child: Icon(
                  Icons.announcement_outlined,
                  size: 25,
                  color: Colors.black.withOpacity(0.6),
                ),
              ),
              Container(
                child: Icon(
                  Icons.wifi_protected_setup,
                  size: 25,
                  color: Colors.black.withOpacity(0.6),
                ),
              ),
              SizedBox(
                width: 16,
              ),
            ],
          ),
        ),

        ///底部标签
        Container(
        ),

        ///底部
        Container(
          width: 343,
          margin: EdgeInsets.only(left:16 ),
          child: Text(
            listmodel.content,
            style: TextStyle(fontSize: 14),
          ),
        ),
        Container(
          width: 61,
          height: 16,
          margin: EdgeInsets.fromLTRB(16, 9.5, 0, 0),
          child: Text(
            "共${listmodel.comments.length}条评论",
            style:
                TextStyle(fontSize: 12, color: Colors.black.withOpacity(0.5)),
          ),
        ),
        Column(
          children: List.generate(
            laudCount,
            (index) {
              return Container(
                  margin: EdgeInsets.only(left: 16, top: 5, right: 16),
                  child: Row(
                    children: <Widget>[
                      Container(
                        child: Text(
                          "${listmodel.comments[index].name}:",
                          style: TextStyle(fontSize: 13),
                        ),
                      ),
                      Text(
                        '${listmodel.comments[index].content}',
                        overflow: TextOverflow.ellipsis, //长度溢出后显示省略号
                        maxLines: 1,
                        style: TextStyle(
                          fontSize: 13.0,
                        ),
                      ),
                    ],
                  ));
            },
          ),
        ),

        ///评论区
        Container(
          child: Row(
            children: <Widget>[
              Container(
                  margin: EdgeInsets.fromLTRB(16, 10, 0, 0),
                  child: CircleAvatar(
                      radius: 13,
                      backgroundImage: AssetImage('assets/icon/qq.png'))),
              Container(
                  width: 280,
                  height: 28,
                  decoration: BoxDecoration(
                    border: Border.all(
                      color: Colors.grey.withOpacity(0.1),
                      width: 1,
                    ),
                    borderRadius: BorderRadius.circular(30),
                    color: Colors.grey.withOpacity(0.1),
                  ),
                  margin: EdgeInsets.fromLTRB(10, 10, 0, 0),
                  child: Container(
                    margin: EdgeInsets.fromLTRB(10, 3, 0, 0),
                    child: Text(
                      "喜欢就评论吧~",
                      style: TextStyle(color: Colors.grey.withOpacity(0.4)),
                    ),
                  ))
            ],
          ),
        ),
      ],
    );
  }
}



///底部提示框
void showModal(BuildContext context){
  showModalBottomSheet(
      context: context,
      isDismissible: true,
      isScrollControlled: false,

      ///下方提示框
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(15),
              topRight: Radius.circular(15))),
      builder: (BuildContext context) {
        return Container(
          alignment: Alignment.center,
          height: 90,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              GestureDetector(
                onTap: () {
                  ///关闭底部提示框
                  Navigator.pop(context);

                  ///举报提示框
                  showDialog(
                    context: context,
                    builder: (context) {
                      return Center(
                          child: Container(
                            alignment: Alignment.center,
                            width: 255,
                            height: 165,

                            ///设置圆角
                            decoration: BoxDecoration(
                              color: Colors.white,
                              //设置四周圆角 角度
                              borderRadius:
                              BorderRadius.all(Radius.circular(10.0)),
                            ),
                            child: Column(
                              // mainAxisSize: MainAxisSize.min,
                              children: <Widget>[
                                Container(
                                  margin: EdgeInsets.only(top: 20),
                                  child: Text("提交举报",
                                      style: TextStyle(
                                        ///设置为下划线
                                        decoration: TextDecoration.none,
                                        color: Colors.black,
                                        fontSize: 18,
                                      )),
                                ),
                                Container(
                                  margin:
                                  EdgeInsets.only(top: 8, bottom: 16),
                                  child: Text("确认举报该动态",
                                      style: TextStyle(
                                        ///设置为下划线
                                        decoration: TextDecoration.none,
                                        color:
                                        Colors.black.withOpacity(0.5),
                                        fontSize: 18,
                                      )),
                                ),
                                Spacer(),

                                ///举报按钮
                                Row(
                                  crossAxisAlignment:
                                  CrossAxisAlignment.center,
                                  children: <Widget>[
                                    GestureDetector(
                                      onTap: () {
                                        Navigator.pop(context);
                                      },
                                      child: Container(
                                        height: 50,
                                        width: 127.5,
                                        alignment: Alignment.center,

                                        ///自定义边框
                                        decoration: BoxDecoration(
                                            border: Border(
                                                top: BorderSide(
                                                    color: Colors.black
                                                        .withOpacity(0.2),
                                                    width: 1),
                                                right: BorderSide(
                                                    color: Colors.black
                                                        .withOpacity(0.2),
                                                    width: 0.5))),

                                        child: Text(
                                          "再想想",
                                          style: TextStyle(

                                            ///设置为下划线
                                              decoration:
                                              TextDecoration.none,
                                              color: Colors.black,
                                              fontSize: 18),
                                        ),
                                      ),
                                    ),
                                    GestureDetector(
                                      onTap: () {
                                        Fluttertoast.showToast(msg: "感谢您的反馈，我们会尽快处理",toastLength: Toast.LENGTH_SHORT,gravity: ToastGravity.BOTTOM,
                                            textColor: Colors.white,
                                            fontSize: 12.0
                                        );
                                        Navigator.pop(context);
                                      },
                                      child: Container(
                                        height: 50,
                                        width: 127.5,
                                        alignment: Alignment.center,
                                        decoration: BoxDecoration(
                                            border: Border(
                                                top: BorderSide(
                                                    color: Colors.black
                                                        .withOpacity(0.2),
                                                    width: 1),
                                                left: BorderSide(
                                                    color: Colors.black
                                                        .withOpacity(0.2),
                                                    width: 0.5))),
                                        child: Text(
                                          "必须举报",
                                          style: TextStyle(

                                            ///设置为下划线
                                              decoration:
                                              TextDecoration.none,
                                              color: Colors.red,
                                              fontSize: 18),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ));
                    },
                  );
                },
                child: Container(
                  child: Text(
                    "举报",
                    style: TextStyle(fontSize: 18),
                  ),
                ),
              ),
              Container(
                height: 20,
              ),
              GestureDetector(
                onTap: () {
                  ///关闭底部提示框
                  Navigator.pop(context);
                },
                child: Container(
                  child: Text(
                    "取消",
                    style: TextStyle(fontSize: 18),
                  ),
                ),
              )
            ],
          ),
        );
      }).then((value){
        print("下拉框的遮罩层已退出");

  });
}





